﻿using System;
using System.Collections;

namespace ObjectPool
{
    class ObjQueue
    {
        private static int maxSize = 2;
        private static readonly Queue objPool = new Queue(maxSize);
        public MyClass GetMyClass()
        {
            MyClass oMyClass;
            if (MyClass.Counter >= maxSize && objPool.Count > 0)
                oMyClass = RetrieveFromPool();
            else
                oMyClass = GetNewMyClass();
            return oMyClass;
        }
        private MyClass GetNewMyClass()
        {
            MyClass myObj = new MyClass();
            objPool.Enqueue(myObj);
            return myObj;
        }
        protected MyClass RetrieveFromPool()
        {
            MyClass myObj;
            if (objPool.Count > 0)
            {
                myObj = (MyClass)objPool.Dequeue();
                MyClass.Counter--;
            }
            else
                myObj = new MyClass();
            return myObj;
        }
    }
    class MyClass
    {
        public static int Counter = 0;
        public MyClass() { ++Counter; }
        private string _Firstname;
        public string Firstname
        {
            get { return _Firstname; }
            set { _Firstname = value; }
        }
    }
}